<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <button id="increment">+1</button>
    <span id="box">0</span>
    <button id="decrement">-1</button>
  </div>
</body>

<script src="myRedux.js"></script>

<script>

  function enhancer (createStore) {
    return function (reducer, preloadState) {
      const store = createStore(reducer, preloadState)
      let dispatch = store.dispatch
      function _dispatch(action) {
        if(typeof action === 'function') {
          action(dispatch)
        } else {
          dispatch(action)
        }
      }
      return {
        ...store,
        dispatch: _dispatch
      }

    }
  }
  
  function reducer(state, action) {
    switch(action.type) {
      case 'increment':
        return state + 1
      case 'decrement':
        return state - 1
      default:
        return state
    }
  }

  const store = createStore(reducer, 0, enhancer)

  document.getElementById('increment').onclick = function() {
    // store.dispatch((dispatch) => {
    //   setTimeout(() => {
    //     dispatch({ type: 'increment' })
    //   }, 1000);
    // })
    store.dispatch({ type: 'increment' })
  }

  document.getElementById('decrement').onclick = function() {
    store.dispatch({ type: 'decrement' })
  }

  store.subscribe(() => {
    document.getElementById('box').innerHTML = store.getState()
  })

</script>

</html>